<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class UserController extends Controller
{

    /**
     * 用户登录页面
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|\think\response\View
     */
    public function login()
    {
        return view('/blog/login');
    }


    /**
     * 用户登录
     * @param Request $request
     *
     * @return $this|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\think\response\Redirect|void
     */
    public function loginStore(Request $request)
    {
        // 验证表单数据
        $this->validate($request, [
            'email'    => 'required|email',
            'password' => 'required',
        ]);

        $user['email']    = $request->input('email');
        $user['password'] = $request->input('password');
        $remember         = boolval($request->input('is_remember'));

        if (\Auth::attempt($user, $remember) === true) {
            return redirect('/');
        }

        return back()->withErrors('账号或密码错误');


    }


    /**
     * 注册页面
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|\think\response\View
     */
    public function register()
    {
        return view('/blog/register');
    }


    /**
     * 注册逻辑
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\think\response\Redirect|void
     */
    public function registerStore(Request $request)
    {
        // 验证表单数据
        $this->validate($request, [
            'nickname' => 'required|unique:users,nickname|min:3|max:8',
            'email'    => 'required|unique:users,email|email',
            'password' => 'required|min:6|max:16|confirmed',
        ]);

        $email    = $request->input('email');
        $password = bcrypt($request->input('password'));
        $nickname = $request->input('nickname');

        User::create(compact('nickname', 'email', 'password'));

        return redirect('/login');

    }


    public function logout()
    {
        \Auth::logout();

        return redirect('/');

    }

}
